const http = require("http");
const fs =require("fs");

var userList =[];

function getData(str){
    var arr = str.split('&');
    var obj = {};
    for(var i=0; i<arr.length; i++){
        var childArr = arr[i].split('=');
        obj[childArr[0]] = childArr[1];
    }
    return obj;
}

http.createServer((req,res)=>{
    var urlObj = new URL(req.url,"htto://localhost:8081");
    var pathname = urlObj.pathname;
    if(pathname =="/"){
        var fileContent = fs.readFileSync("./post.html");
        res.writeHeader(200,{"Content-Type":"text/html;charset=uts-8"})
        res.write(fileContent);
        res.end();
    }
    else if(pathname == "/list"){
        var fileContent = fs.readFileSync("./list.html");
        res.writeHeader(200,{"Content-Type":"text/html;charset=uts-8"})
        res.write(fileContent);
        res.end();
    }
    else if(pathname=="/save"){
        var str ="";
        req.on("data",(chunk)=>{
            str += chunk;
        })       
        req.on("end",()=>{
            var postObj = getData(str);
            userList.push(postObj);
            res.end("submit success");
        })
        
    }
    else if(pathname=="/getlist"){
        var userStr = JSON.stringify(userList);
        res.writeHeader(200,{"Content-Type":"text/html;charset=uts-8"});
        res.end(userStr);
    }
    //删除数据过程 接受请求、del?deluser=zhangsan 
    //根据username
    else if(pathname=="/del"){
        var deluser = urlObj.searchParams.get("deluser");
        for(var i=0; i<userList.length; i++){
            if(userList[i]["username"]==deluser){
                userList.splice(i,1);
                res.end("delete success");
            }
        }
    }

}).listen(8081)